package com.newki.profile.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;

import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.newki.profile.R;

public class MyBottomSheetDialog extends BottomSheetDialogFragment {

    private BottomSheetBehavior<FrameLayout> behavior;

    private static int expandedHeight;

    private int dialogInitialY;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(STYLE_NORMAL, R.style.StyleBottomSheetDialogBg);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.layout_item_dialog_more, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.findViewById(R.id.vDownClose).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });

        // 设置可以拖动的特定元素
        View draggableElement = view.findViewById(R.id.drag_handle);
        draggableElement.setOnTouchListener(new View.OnTouchListener() {
            private float initialY;
            private float deltaY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        initialY = event.getY();
                        dialogInitialY = getDialog().getWindow().getDecorView().getTop();
                        Log.e("touch", "start:initialY:" + initialY + "dialogInitialY:" + dialogInitialY);
                        return true;
                    case MotionEvent.ACTION_MOVE:
                        deltaY = event.getY() - initialY;
                        int newY = dialogInitialY + (int) deltaY;
                        if (newY < 0) {
                            return false;
                        }
                        getDialog().getWindow().getDecorView().setTop(newY);
                        Log.e("touch", "move: " + deltaY + "newY:" + newY);
                        return true;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        Log.e("touch", "cancel deltaY: " + deltaY + "behavior.getPeekHeight() / 2:" + behavior.getPeekHeight() / 2);
                        if (Math.abs(deltaY) > behavior.getPeekHeight() / 2) {
                            behavior.setState(BottomSheetBehavior.STATE_HIDDEN);
                        } else {
                            // behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                            getDialog().getWindow().getDecorView().setTop(dialogInitialY);
//                            View rootView = getDialog().getWindow().getDecorView();
//                            rootView.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.bottom_sheet_set_top_anim));
//                            rootView.offsetTopAndBottom(dialogInitialY);
                        }
                        return true;
                }
                return false;
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        BottomSheetDialog dialog = (BottomSheetDialog) getDialog();
        if (dialog == null) return;

        Window window = dialog.getWindow();

        if (window == null) return;

//        FrameLayout bottomSheet = dialog.findViewById(R.id.design_bottom_sheet1);
        FrameLayout bottomSheet = dialog.findViewById(com.google.android.material.R.id.design_bottom_sheet);
        window.setWindowAnimations(R.style.BottomSheetDialogAnimation); // 设置自定义动画

        if (bottomSheet == null) return;

        behavior = BottomSheetBehavior.from(bottomSheet);

        ViewGroup.LayoutParams bottomSheetLayoutParams = bottomSheet.getLayoutParams();
        bottomSheetLayoutParams.height = getBottomSheetDialogDefaultHeight();
        bottomSheet.setLayoutParams(bottomSheetLayoutParams);

        expandedHeight = bottomSheetLayoutParams.height;
        int peekHeight = (int) (expandedHeight / 1.3); //Peek height to 70% of expanded height (Change based on your view)

        behavior.setPeekHeight(peekHeight);
        behavior.setDraggable(false);
//        behavior.setHideable(false);

        // 获取初始高度
//        final int initialHeight = bottomSheet.getHeight();

        // 设置 BottomSheetBehavior 回调
        behavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
//                if (newState == BottomSheetBehavior.STATE_DRAGGING) {
//                    // 处理拖动状态
//                } else if (newState == BottomSheetBehavior.STATE_SETTLING) {
//                    // 处理结算状态
//                }
                // 当状态为隐藏时，关闭 dialog
                if (newState == BottomSheetBehavior.STATE_HIDDEN) {
                    dismiss();
                }
                else if (newState == BottomSheetBehavior.STATE_EXPANDED) {
                    getDialog().getWindow().getDecorView().setTop(dialogInitialY);
                    Log.e("reset", "now");
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                // 如果向下滑动超过一半高度，设置状态为隐藏，否则设置状态为展开
//                if (slideOffset < -0.5f) {
//                    behavior.setState(BottomSheetBehavior.STATE_HIDDEN);
//                } else if (slideOffset >= 0) {
//                    behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
//                }
            }
        });
    }

    public static void show(FragmentActivity activity) {
        MyBottomSheetDialog bottomSheet = new MyBottomSheetDialog();
        bottomSheet.show(activity.getSupportFragmentManager(), bottomSheet.getTag());
    }

    private int getBottomSheetDialogDefaultHeight() {
        return getWindowHeight() * 90 / 100;
    }

    private int getWindowHeight() {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        ((Activity) requireContext()).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.heightPixels;
    }
}
